<script lang="ts" setup>
// hooks
import useSelect from '@/hooks/select';

const { canvasEditor } = useSelect();
const state = reactive({
  hasClipPath: false,
  imageBoxLoading: false,
});

const handleClick = async () => {
  state.imageBoxLoading = true;
  await canvasEditor.addClipPathToImage(
    'https://paint-2025.oss-cn-hangzhou.aliyuncs.com/other/1755355099880-123.svg'
  );
  state.imageBoxLoading = false;
  state.hasClipPath = true;
};

const handleEditClick = async () => {
  await canvasEditor.editClipPathToImage();
};

const handleDelClick = () => {
  const activeObject = canvasEditor.canvas.getActiveObjects()[0];

  if (!activeObject) return;
  activeObject.set({ clipPath: null });
  canvasEditor.canvas.renderAll();
  state.hasClipPath = false;
};

const init = () => {
  const activeObject = canvasEditor?.canvas?.getActiveObjects()?.[0];

  if (!activeObject) return;
  if (activeObject.clipPath) {
    state.hasClipPath = true;
  } else {
    state.hasClipPath = false;
  }
  console.log(state.hasClipPath);
};

onMounted(() => {
  canvasEditor.on('selectOne', init);
  init();
});

onBeforeUnmount(() => {
  canvasEditor.off('selectOne', init);
});
</script>

<template>
  <span v-if="!state.hasClipPath" @click="handleClick()">添加相框</span>
  <template v-else>
    <span class="edit-image-box" @click="handleEditClick()">编辑相框</span>
    <span class="del-image-box" @click="handleDelClick()">删除相框</span>
  </template>
  <Spin fix :show="state.imageBoxLoading">
    <div class="loader">
      <svg class="circular" viewBox="25 25 50 50">
        <circle
          class="path"
          cx="50"
          cy="50"
          r="20"
          fill="none"
          stroke-width="5"
          stroke-miterlimit="10"
        ></circle>
      </svg>
    </div>
  </Spin>
</template>

<style lang="less" scoped>
.edit-image-box,
.del-image-box {
  font-size: 12px;
  font-weight: bold;
  padding: 0 5px;
  background-color: var(--background-primary-color);
  border-radius: 4px;
  display: inline-block;
}
.del-image-box {
  margin-left: 2px;
}
</style>
